package com.newsee.remote.idm.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.newsee.remote.common.bean.JsonResult;
import com.newsee.remote.common.bean.JsonReturn;
import com.newsee.remote.common.database.entity.SystemDepartmentThird;
import com.newsee.remote.common.database.mapper.SystemDepartmentThirdMapper;
import com.newsee.remote.common.dto.idm.SystemDepartmentDTO;
import com.newsee.remote.common.enumeration.OrgStatusChangeEnum;
import com.newsee.remote.common.exception.ServiceException;
import com.newsee.remote.common.utils.tools.XmlBuildUtil;
import com.newsee.remote.common.utils.webservice.HttpWebserviceExecutor;
import com.newsee.remote.idm.service.ISystemDepartmentThirdService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.time.LocalDateTime;
import java.util.List;

import static org.apache.catalina.manager.Constants.CHARSET;

/**
 * <p>
 * 部门服务实现类
 * </p>
 *
 * @author liangzhichen
 * @since 2019-07-11
 */
@Slf4j
@Service
public class SystemDepartmentThirdServiceImpl extends ServiceImpl<SystemDepartmentThirdMapper, SystemDepartmentThird> implements ISystemDepartmentThirdService {

    /**
     * 事务ID前缀—组织
     */
    private final static String BIZTRANSACTIONID_PRE_ORG = "WY_WZXTOrg_301_";

    /**
     * 融创标准请求_ORG
     */
    private final static String XMLNS_STR_ORG = "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:v1=\"http://www.ekingwin.com/esb/header/v1\" xmlns:pub=\"http://www.ekingwin.com/esb/PUBLIC_SUNAC_301_queryIdmOrgData\">\n";

    /**
     * 循环调用idm信息查询接口，每页100，一天同步一次
     */
    private final static int TIMES = 100;

    @Value("${idmOrgUrl}")
    private String idmOrgUrl;

    @Value("${systemOrgID}")
    private String systemOrgID;

    @Value("${accountOrg}")
    private String accountOrg;

    @Value("${passwordOrg}")
    private String passwordOrg;

    @Value("${idmOrgMethod}")
    private String idmOrgMethod;

    @Override
    public JsonResult sync(SystemDepartmentDTO departmentDTO) {
        String departmentID = departmentDTO.getDepartmentID();

        //校验是新增还是修改
        QueryWrapper<SystemDepartmentThird> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("DepartmentID", departmentID);
        SystemDepartmentThird systemDepartment = getOne(queryWrapper);
        LocalDateTime now = LocalDateTime.now();
        //新增
        if (null == systemDepartment) {
            systemDepartment = new SystemDepartmentThird();
        }//修改
        else {
            systemDepartment.setUpdateTime(now);
        }

        //部门ID
        systemDepartment.setDepartmentID(departmentID);
        String fatherDepartmentID = departmentDTO.getFatherDepartmentID();
        //父部门ID
        if (StringUtils.isNotBlank(fatherDepartmentID)) {
            systemDepartment.setFatherDepartmentID(fatherDepartmentID);
        }
        //部门名称
        String departmentName = departmentDTO.getDepartmentName();
        if (StringUtils.isNotBlank(departmentName)) {
            systemDepartment.setDepartmentName(departmentName);
        }
        //状态
        Integer status = departmentDTO.getStatus();
        if (null != status) {
            systemDepartment.setStatus(status);
        }
        //排序
        Integer orderID = departmentDTO.getOrderID();
        if (null != orderID) {
            systemDepartment.setOrderID(orderID);
        }

        saveOrUpdate(systemDepartment);
        return JsonReturn.succ();
    }

    @Override
    public JsonResult sunacOrg(String startTime, String endTime) {
        for (int i = 1; i <= TIMES; i++) {
            //xml请求封装
            String params = XmlBuildUtil.makeXml(XMLNS_STR_ORG, idmOrgMethod, systemOrgID, accountOrg, passwordOrg, i, BIZTRANSACTIONID_PRE_ORG, startTime, endTime);
            String response;
            try {
                response = HttpWebserviceExecutor.doHttpMethod(idmOrgUrl, params);
                if (StringUtils.isNotEmpty(response)) {
                    //当页数据为空，停止
                    if ("<LIST></LIST>".equals(response)) {
                        break;
                    } else {
                        handleResponse(response);
                    }
                }
            } catch (Exception e) {
                //同步出错，停止同步
                break;
            }
        }
        return JsonReturn.succ();
    }


    /**
     * 解析返回结果
     */
    private void handleResponse(String list) throws ServiceException {
        try {
            SAXReader reader = new SAXReader();
            // 根据字符串构建字节数组输入流
            InputStream isList = new ByteArrayInputStream(list.getBytes(CHARSET));
            // 命令阅读器从输入流中读取文档对象
            Document documentList = reader.read(isList);
            // 获得文档对象的根节点
            List<Element> orgs = documentList.getRootElement().elements();
            for (Element org : orgs) {
                SystemDepartmentDTO orgDTO = new SystemDepartmentDTO();

                Element organID = org.element("OrganNumber");
                if (null != organID) {
                    orgDTO.setDepartmentID(organID.getText());
                }

                Element organName = org.element("OrganName");
                if (null != organName) {
                    orgDTO.setDepartmentName(organName.getText());
                }

                Element organParentID = org.element("OrganParentNo");
                if (null != organParentID) {
                    orgDTO.setFatherDepartmentID(organParentID.getText());
                }

                Element organStatus = org.element("OrganStatus");
                if (null != organStatus) {
                    orgDTO.setStatus(OrgStatusChangeEnum.getTextByCode(organStatus.getText()));
                }

                Element organSortCode = org.element("OrganSortCode");
                if (null != organSortCode) {
                    try {
                        String sortCode = organSortCode.getText();
                        if (StringUtils.isNotEmpty(sortCode)) {
                            String[] codes = sortCode.split("!");
                            String code = codes[codes.length - 1];
                            orgDTO.setOrderID(Integer.parseInt(code));
                        }
                    } catch (Exception e) {
                        log.warn("排序号为空，或者格式有误！");
                    }
                }

                sync(orgDTO);
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("组织增量同步出错" + e.getMessage());
            throw new ServiceException();
        }
    }


}
